//
//  VersionUpdateClass.m
//  Growth
//
//  Created by Hobo.Chen on 7/19/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "VersionUpdateClass.h"

#import "WebRequest.h"

#import "WebConnection.h"

#import "CJSONDeserializer.h"


static VersionUpdateClass *_versionUpdateClass = nil;

@implementation VersionUpdateClass

+ (id)shareVersionUpdateClass
{
    if (!_versionUpdateClass) {
        _versionUpdateClass = [[VersionUpdateClass alloc] init];

    }
    
    return _versionUpdateClass;
}



-(void)VersionUpdateMethord{
    
    //避免一直弹版本警告
    isCheckVersion = NO;
    
    NSString *bundleVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] ;
    

    NSMutableURLRequest *request = [WebRequest  versionUpdateWith:@"iphone" version:bundleVersion ];
    CLog(@"request %@", request);
    
    [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];   
}


- (void)checkVersion{
    
    isCheckVersion = YES;
    [self VersionUpdateMethord];
    
}


- (NSDictionary *)parseJSON:(NSMutableData *)data {
	CLog(@"Parsing JSON");
	NSError *error = nil;
    
	NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];
	CLog(@"connection data dict %@",dictionary);
    
    
	return dictionary;
}


#pragma mark -

// NSURLConnection Delegate Methods. You would want to include more for error handling //
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    NSHTTPURLResponse  *httpResponse = ( NSHTTPURLResponse  *)response;
    
    statusCode = [httpResponse  statusCode ];
    
    CLog( @"status code = %d" ,statusCode);
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data {
	CLog(@"Recieving Data...");
    CLog(@"versionUpdate Receive data ");
    
    NSDictionary * receiveDictionary = [self parseJSON:data];
    CLog(@"versionUpdate ReceiveDictionary %@", receiveDictionary);
    
    [self didReceiveUpdateInfo:receiveDictionary];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	
    if (isCheckVersion) {
        [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME];
    }
    
    CLog(@"versionUpdate error %@", error);
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	CLog(@"Fininshed Loading...");
    
    CLog(@"versionUpdate Finish loading %@", connection);
}

- (void)didReceiveUpdateInfo:(NSDictionary *)updateInfoDict{
    
    if (statusCode == 200 && ![[updateInfoDict objectForKey:@"version"] isMemberOfClass:[NSNull class]]) {
        
        CLog(@"update info dict %@", updateInfoDict);
        
        NSString *version = [updateInfoDict objectForKey:@"version"];
        NSString *isNecessaryStr = [updateInfoDict objectForKey:@"enforce"];
        BOOL isNecessary = NO;
        if (isNecessaryStr) {
            isNecessary = [isNecessaryStr boolValue];
        }
        
        NSString *currentVersion;
        
        [[NSUserDefaults standardUserDefaults] setValue:version forKey:GROWTH_LASTEST_VERSION_KEY];
        
        NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
        currentVersion = [info objectForKey:(NSString *)kCFBundleVersionKey];
        
        float currentVersionFloat = [currentVersion floatValue];
        float lastestVersionFloat = [version floatValue];
        
        CLog(@"New version %f  Locale version %f", lastestVersionFloat, currentVersionFloat);
        
        NSString *description = [updateInfoDict objectForKey:@"description"];
        if (description) {
            description = [description stringByReplacingOccurrencesOfString:@";" withString:@"\n"];
        }
        
        @try {
            if (currentVersionFloat <lastestVersionFloat ) {
                
                if (isNecessary) {
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"升级到%@版本",version] message:description 
                                                                   delegate:self 
                                                          cancelButtonTitle:nil otherButtonTitles:nil];
                    
                    [alert addButtonWithTitle:@"确认"];
                    
                    alert.delegate = self;
                    alert.tag = 110;
                    
                    [alert show];
                    [alert release];
                }
                else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"升级到%@版本",version] message:description 
                                                                   delegate:self 
                                                          cancelButtonTitle:@"下次再说" otherButtonTitles:nil];
                    
                    [alert addButtonWithTitle:@"确认"];
                    
                    alert.delegate = self;
                    
                    [alert show];
                    [alert release];
                }
                
                
            }
            else{
                
                if (isCheckVersion) {
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"已经是最新版本%.1f",currentVersionFloat] 
                                                                   delegate:self 
                                                          cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    
                    
                    GrowthAppDelegate *appDelegate = 
                    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
                    
                    alert.delegate = appDelegate;
                    
                    
                    [alert show];
                    [alert release];
                    
                    
                }
                
                
            }
        }
        @catch (NSException *exception) {
            
        }
        @finally {
            
        }
    }
    else{
        
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //110为必须更新版本状态
    if (alertView.tag == 110) {
        if (buttonIndex == 0) {
            NSString *str = [NSString stringWithFormat:@"http://itunes.apple.com/app/id%@?mt=8",@"525681769"];  
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }
    }
    else {
        if (buttonIndex == 1) {
            
            NSString *str = [NSString stringWithFormat:@"http://itunes.apple.com/app/id%@?mt=8",@"525681769"];  
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
            
        }
    }
    
    
}


@end
